package com.example.supermarket_back.config.filter;


import com.example.supermarket_back.config.cache.CacheConfig;
import com.example.supermarket_back.utils.CommonUtil;
import com.example.supermarket_back.utils.JWTUtils;
import com.example.supermarket_back.utils.StringTools;
import com.example.supermarket_back.utils.constants.ErrorEnum;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//自定义拦截器
public class RequestInterceptor implements HandlerInterceptor {

    private final CacheConfig cacheConfig;

    public RequestInterceptor(CacheConfig cacheConfig) {
        this.cacheConfig = cacheConfig;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头中的令牌
        String token = request.getHeader("token");
        if(!StringTools.isNullOrEmpty(token)&& JWTUtils.verify(token)&&cacheConfig.exists(token)){
            try {
                String user = JWTUtils.getInfo(token,"user");
                assert user != null;
                if(user.equals(cacheConfig.getData(token))){
                    return true;
                }
            }catch (Exception e){
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().println(CommonUtil.errorJson(ErrorEnum.E_401));
                return false;
            }
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(CommonUtil.errorJson(ErrorEnum.E_401));
        return false;
    }
}
